require('./index.css');
const _user_service = require('../../service/user_service.js');
const _common_util = require('../../util/util_1.js');

const register = {
    init: function() {
        this.bindEvent();
        this.refreshCaptcha(); // 初始化时加载验证码
        return this;
    },
    bindEvent: function() {
        const _this = this;
        const registerForm = document.querySelector('form');
        const usernameInput = document.getElementById('username');
        const feedbackDiv = document.getElementById('feedback');
        const captchaImage = document.getElementById('captchaImage');

        // 用户名输入框失去焦点时检查用户名
        usernameInput.addEventListener('blur', function() {
            const username = this.value.trim();
            if (username) {
                _user_service.checkUsername(username, function() {
                    feedbackDiv.textContent = "";
                }, function(errMsg) {
                    feedbackDiv.textContent = errMsg;
                    feedbackDiv.style.color = 'red';
                });
            }
        });

        // 验证码图片点击事件
        captchaImage.addEventListener('click', function() {
            _this.refreshCaptcha();
        });

        // 表单提交事件
        registerForm.addEventListener('submit', function(event) {
            // 阻止默认提交事件
            event.preventDefault();


            // 获取表单数据
            const formData = {
                username: usernameInput.value,
                password: registerForm.password.value,
                email: registerForm.email.value,
                age: registerForm.age.value,
                responsibility: registerForm.responsibility.value,
                captcha: registerForm.captcha.value
            };

            // 发送注册请求
            _user_service.register(formData, function(res) {
              window.location.href = '/view/login.html?message=注册成功，请登录！';
            }, function(errMsg) {
                registerForm.captcha.value = '';
                alert('注册错误:', errMsg);
                console.error('注册错误:', errMsg);
                // 请求失败时刷新验证码
                _this.refreshCaptcha();
            });
        });
    },
    // 刷新验证码
    refreshCaptcha: function() {
        const registerForm = document.querySelector('form');
        registerForm.captcha.value = '';
        const captchaImage = document.getElementById('captchaImage');
        // 在URL后添加时间戳，防止浏览器缓存
        captchaImage.src = _user_service.getCaptcha() + '?t=' + new Date().getTime();
    }
};

$(function() {
    register.init();
});
